package com.tuananh.radnom.model.utils;

import java.util.ArrayList;
import java.util.StringTokenizer;

import com.tuananh.radnom.model.iputils.IPFilter;
import com.tuananh.radnom.model.iputils.IPRange;

public class IPUtils {

	public static int ipCompare(String ip, String comparedIP) {
		StringTokenizer tokenizerIP = new StringTokenizer(ip, ".");
		StringTokenizer tokenizerCompared = new StringTokenizer(comparedIP, ".");
		if (tokenizerIP.countTokens() != tokenizerCompared.countTokens())
			return -2;
		while (tokenizerIP.hasMoreElements()) {
			int byteIP = Integer.parseInt(tokenizerIP.nextToken());
			int byteCompared = Integer.parseInt(tokenizerCompared.nextToken());

			if (byteIP == byteCompared)
				continue;
			if (byteIP > byteCompared)
				return 1;
			else
				return -1;
		}
		return 0;
	}

	public static int filterValidate(IPFilter filter, String ip) {
		String end = filter.getEndIP(), start = filter.getStartIP();
		int startRS = ipCompare(ip, start) ;
		if (startRS == 0) return 0;// in range
		if (startRS > 0) {
			if (end != null) {
				int rs = ipCompare(ip, end);
				if (rs <= 0) {
					if (rs == -2)
						return -2; // not the right format
					return 0; // in range
				}
				else return 1;
			}
		}
		return -1;// in range
	}

	public static boolean inRange(IPRange range, String ip) {
		// Check for exclude first
		ArrayList<IPFilter> exclude = range.getExcludeIps();
		for (IPFilter filter : exclude) {
			if (filterValidate(filter, ip) == 0)
				return false;
		}

		ArrayList<IPFilter> include = range.getIncludeIps();
		for (IPFilter filter : include) {
			if (filterValidate(filter, ip) == 0)
				return true;
		}
		return false;
	}
}
